package com.xoa.service.performance;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.duties.DutiesManagementMapper;
import com.xoa.dao.performance.ScoreFlowMapper;
import com.xoa.dao.performance.ScoreFlowUsersMapper;
import com.xoa.dao.performance.ScoreGroupMapper;
import com.xoa.dao.performance.ScoreItemMapper;
import com.xoa.dao.scoreflowitem.ScoreFlowItemMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.duties.UserPost;
import com.xoa.model.performance.*;
import com.xoa.model.scoreflowitem.ScoreFlowItem;
import com.xoa.model.users.Users;
import com.xoa.service.sms.SmsService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ExcelUtil;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;

import java.util.*;


@Service
public class ScoreFlowUserService {

    @Autowired
    private ScoreFlowUsersMapper scoreFlowUsersMapper;

    @Autowired
    private ScoreFlowMapper scoreFlowMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private ScoreGroupMapper scoreGroupMapper;

    @Autowired
    private ScoreItemMapper scoreItemMapper;

    @Autowired
    private ScoreFlowItemMapper scoreFlowItemMapper;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private SysCodeMapper sysCodeMapper;

    @Resource
    private SmsService smsService;
    @Resource
    DepartmentMapper departmentMapper;
    @Resource
    HttpServletResponse response;
    @Resource
    HttpServletRequest request;
    @Autowired
    private DutiesManagementMapper dutiesManagementMapper;
    /**
     * @接口说明: 添加接口
     * @日期: 2020/7/17
     * @作者: 张航宁
     */
    public BaseWrapper insert(ScoreFlowUsers scoreFlowUsers){
        BaseWrapper baseWrapper = new BaseWrapper();
        scoreFlowUsersMapper.insertSelective(scoreFlowUsers);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @接口说明: 编辑接口
     * @日期: 2020/7/17
     * @作者: 张航宁
     */
    public BaseWrapper update(ScoreFlowUsers scoreFlowUsers){
        BaseWrapper baseWrapper = new BaseWrapper();
        scoreFlowUsersMapper.updateByPrimaryKeySelective(scoreFlowUsers);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }


    /**
     * @接口说明: 查询接口
     * @日期: 2020/7/17
     * @作者: 张航宁
     */
    public BaseWrapper select(ScoreFlowUsers scoreFlowUsers, PageParams pageParams){
        BaseWrapper baseWrapper = new BaseWrapper();
        Map<String,Object> map = new HashMap<>();
        map.put("page",pageParams);
        map.put("userId",scoreFlowUsers.getUserId());
        map.put("status",scoreFlowUsers.getStatus());
        map.put("scoreFlowId",scoreFlowUsers.getScoreFlowId());

        List<ScoreFlowUsers> scoreFlowUsers1 = scoreFlowUsersMapper.selectFlowUsers(map);

        baseWrapper.setData(scoreFlowUsers1);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);

        return baseWrapper;
    }

    /**
     * @接口说明: 删除接口
     * @日期: 2020/7/17
     * @作者: 张航宁
     */
    public BaseWrapper delete(String ids){
        BaseWrapper baseWrapper = new BaseWrapper();

        scoreFlowUsersMapper.deleteByIds(ids.split(","));
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @接口说明: 根据scoreFlowId更新
     * @日期: 2020/7/17
     * @作者: 张航宁
     */
    public BaseWrapper updateByFlowId(ScoreFlowUsers scoreFlowUsers){
        BaseWrapper baseWrapper = new BaseWrapper();
        scoreFlowUsersMapper.updateByFlowId(scoreFlowUsers);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @接口说明: 获取考核任务下的被考核人
     * @日期: 2020/7/18
     * @作者: 张航宁
     */
    public BaseWrapper selFlowUsers(HttpServletRequest request, HttpServletResponse response, PageParams pageParams, String userId, Integer flowId, Boolean export){
        BaseWrapper baseWrapper = new BaseWrapper();
        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(flowId);
        if(scoreFlowWithBLOBs!=null){
            ScoreGroupWithBLOBs scoreGroupWithBLOBs = scoreGroupMapper.selectByPrimaryKey(scoreFlowWithBLOBs.getGroupId());
            if(!StringUtils.checkNull(scoreFlowWithBLOBs.getParticipant())){
                // 初始化返回参数
                List<ScoreFlowUsers> scoreFlowUsers = new ArrayList<>();
                List<Users> users = new ArrayList<>();
                // 把userId串拆分成数组
                String[] userIdArr = scoreFlowWithBLOBs.getParticipant().split(",");
                // 部门id串
                String[] deptIdArr = null;
                if (!StringUtils.checkNull(scoreFlowWithBLOBs.getParticipantDept())) {
                    deptIdArr = scoreFlowWithBLOBs.getParticipantDept().split(",");
                }
                // 判断是否是查询接口 userId为空就是普通的分页查询

                if(StringUtils.checkNull(userId)){
                    if(pageParams!=null&&pageParams.getUseFlag()!=null&&pageParams.getUseFlag()){
                        String[] resultArr = {};
                        // 分页计算
                        // 给默认值 防止前端传递错误数据
                        Integer page = pageParams.getPage();
                        Integer pageSize = pageParams.getPageSize();
                        page = page < 1 ? 1 : page;
                        pageSize = pageSize < 0 ? 5 : pageSize;
                        int arrLength = userIdArr.length;
                        Integer minIndex = (page - 1) * pageSize;
                        // 判断是否超出总数大小
                        if (minIndex < arrLength) {
                            if (page * pageSize > arrLength) {
                                pageSize = arrLength - minIndex;
                            }
                            resultArr = new String[pageSize];
                            for (int i = 0; i < pageSize; i++) {
                                resultArr[i] = userIdArr[minIndex];
                                ++minIndex;
                            }
                        }
                        users = usersMapper.getUsersByUserIdsOrder(resultArr);

                    } else {
                        users = usersMapper.getUsersByUserIdsOrder(userIdArr);
                    }
                } else {
                    for (String userId2:userIdArr) {
                        userId = userId.replace(",","");
                        if(userId2.equals(userId)){
                            Users usersByuserId = usersMapper.findUsersByuserId(userId);
                            users.add(usersByuserId);
                        }
                    }
                }

                // 新建变量记录部门id串
                int deptIdArrNum = 0;
                for (Users u:users) {
                    ScoreFlowUsers scoreFlowUser = new ScoreFlowUsers();
                    scoreFlowUser.setUserId(u.getUserId());
                    if (null == deptIdArr || deptIdArr.length==0 || ",".equals(deptIdArr[deptIdArrNum].substring(deptIdArr[deptIdArrNum].length() -1,deptIdArr[deptIdArrNum].length()))) {//数组为0  或者传空
                        scoreFlowUser.setDeptName(u.getDeptName());
                        scoreFlowUser.setDeptId(String.valueOf(u.getDeptId()));
                    }else {
                        scoreFlowUser.setDeptName(departmentMapper.getDeptNameById(Integer.parseInt(deptIdArr[deptIdArrNum])));
                        scoreFlowUser.setDeptId(deptIdArr[deptIdArrNum]);
                    }
                    deptIdArrNum += 1;

                    scoreFlowUser.setUserName(u.getUserName());
                    scoreFlowUser.setUserPrivName(u.getUserPrivName());
                    scoreFlowUser.setPaperName(scoreGroupWithBLOBs.getGroupName());


                    Map<String,Object> map = new HashMap<>();
                    map.put("userId",u.getUserId());
                    map.put("scoreFlowId",flowId);
                    int paperCount = scoreFlowUsersMapper.selectCount(map);
                    scoreFlowUser.setPaperCount(paperCount);
                    map.put("sql","and status != 0");
                    int downCount = scoreFlowUsersMapper.selectCount(map);
                    scoreFlowUser.setDownCount(downCount);
                    // 计算百分比
                    if(paperCount!=0){
                        NumberFormat percentInstance = NumberFormat.getPercentInstance();
                        percentInstance.setMaximumFractionDigits(2);
                        scoreFlowUser.setPercentage(percentInstance.format(downCount/paperCount));
                    }

                    // 计算得分
                    Double scoreCount = 0.0;
                    if("3".equals(scoreFlowWithBLOBs.getFlowFlag())){
                        List<ScoreFlowUsers> scoreFlowUsers2 = scoreFlowUsersMapper.selectFlowUsers(map);
                        for(int i=0,size=scoreFlowUsers2.size();i<size;i++){
                            ScoreFlowUsers scoreFlowUsers3 = scoreFlowUsers2.get(i);
                            Double score = scoreFlowUsers3.getScore();
                            scoreCount+=score*scoreFlowUsers3.getAssessorWeight()*scoreFlowUsers3.getPrivWeight();
                        }
                        scoreFlowUser.setScoreCount(new BigDecimal(scoreCount).setScale(2, RoundingMode.UP).toString());
                    }

                    scoreFlowUsers.add(scoreFlowUser);
                }

                if(export!=null&&export){
                    try{
                        HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead(scoreFlowWithBLOBs.getFlowTitle().replaceAll("[/\\\\:*?|]", "&")+"（360°员工个人能力测评评分汇总）", 9);
                        String[] secondTitles = {"姓名","用户角色","部门名称","问卷名称","问卷数量","完成数量","完成百分比","考核得分"};
                        HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                        String[] beanProperty = {"userName","userPrivName","deptName","paperName","paperCount","downCount","percentage","scoreCount"};

                        HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, scoreFlowUsers, beanProperty);
                        ServletOutputStream out = response.getOutputStream();

                        String filename = scoreFlowWithBLOBs.getFlowTitle()+"（360°员工个人能力测评评分汇总）.xls";
                        filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                        response.setContentType("application/vnd.ms-excel");
                        response.setHeader("content-disposition", "attachment;filename=" + filename);
                        workbook.write(out);
                        out.close();
                    }catch (Exception e){

                    }

                }
                baseWrapper.setData(scoreFlowUsers);
                if(pageParams.getUseFlag()){
                    baseWrapper.setTotle(userIdArr.length);
                }
            }
        }
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @接口说明: 获取某个考核任务下的 被考核人员的所有考核人
     * @日期: 2020/7/20
     * @作者: 张航宁
     */
    public BaseWrapper selAssessors(String userId,Integer scoreFlowId){
        BaseWrapper baseWrapper = new BaseWrapper();

        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("scoreFlowId",scoreFlowId);


        Map<String,Object> result = new HashMap<>();

        List<ScoreFlowUsers> privUsers1 = new ArrayList<>(); // 上级
        List<ScoreFlowUsers> privUsers2 = new ArrayList<>(); // 平级
        List<ScoreFlowUsers> privUsers3 = new ArrayList<>(); // 下级

        List<ScoreFlowUsers> scoreFlowUsers = scoreFlowUsersMapper.selectFlowUsers(map);
        for (ScoreFlowUsers scoreFlowUser: scoreFlowUsers) {
            String assessor = scoreFlowUser.getAssessor();
            Users users = usersMapper.SimplefindUsersByuserId(assessor);
            if(users!=null){
                scoreFlowUser.setAssessorName(users.getUserName());
            }
            if(scoreFlowUser.getPrivType()==1){
                privUsers1.add(scoreFlowUser);
            } else if(scoreFlowUser.getPrivType()==2){
                privUsers2.add(scoreFlowUser);
            } else if(scoreFlowUser.getPrivType()==3){
                privUsers3.add(scoreFlowUser);
            }
        }

        result.put("privUsers1",privUsers1);
        result.put("privUsers2",privUsers2);
        result.put("privUsers3",privUsers3);

        baseWrapper.setData(result);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @接口说明: 设置评价人员
     * @日期: 2020/7/20
     * @作者: 张航宁
     */
    public BaseWrapper setAssessors(HttpServletRequest request, ScoreFlowUsers scoreFlowUsers, String insertType, String userIds){
        BaseWrapper baseWrapper = new BaseWrapper();

        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(scoreFlowUsers.getScoreFlowId());



        // privWeightStr 的格式为 级别类型|权重占比,  如 1|0.4,
        Map<String,String> privWeightMap = new HashMap<>();
        String privWeightStr = scoreFlowUsers.getPrivWeightStr();
        if(!StringUtils.checkNull(privWeightStr)){
            String[] split = privWeightStr.split(",");
            for (String privs:split){
                if(!StringUtils.checkNull(privs)){
                    String[] privAndWeight = privs.split("\\|");
                    if(privAndWeight.length>1){
                        privWeightMap.put(privAndWeight[0],privAndWeight[1]);
                    }
                }
            }
        }
        // 如果是自评 增加自评的评分占比
        if(scoreFlowWithBLOBs.getIsSelfAssessment()==1){
            privWeightMap.put("4","1");
        }

        // assessorWeightStr 的格式为 级别类型*用户userId|权重占比,  如 1*admin|0.4,

        // 1是给该任务下的所有人员设置
        if("1".equals(insertType)){
            String participant = "";
            if(StringUtils.checkNull(userIds)){
                participant = scoreFlowWithBLOBs.getParticipant();
            } else {
                participant = userIds;
            }
            //先存储考核角色  循环后会把值给替换
            String assessmentRole = scoreFlowUsers.getAssessmentRole();
            if (!StringUtils.checkNull(participant)) {
                String[] userIds2 = participant.split(",");
                for (String userId: userIds2) {
                    scoreFlowUsers.setUserId(userId);
                    scoreFlowUsers.setAssessmentRole(assessmentRole);
                    insertWithWeightStr(scoreFlowUsers, privWeightMap,scoreFlowWithBLOBs.getIsSelfAssessment());
                }
            }
        } else {
            insertWithWeightStr(scoreFlowUsers, privWeightMap,scoreFlowWithBLOBs.getIsSelfAssessment());
        }

        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    private void insertWithWeightStr(ScoreFlowUsers scoreFlowUsers, Map<String, String> privWeightMap,Integer isSelfAssessment) {
        String assessorWeightStr = scoreFlowUsers.getAssessorWeightStr();
        Map<String,Object> newAssessor = new HashMap<>();  // 所有的考核人数据 用于下面判断多余数据
        Map<String,Object> paraMap = new HashMap<>();   // 查询条件参数

        //添加考核角色
        String[] role = null;
        //添加变量 记录考核角色
        int roleNum = 0;
        if (!StringUtils.checkNull(scoreFlowUsers.getAssessmentRole())){
            role = scoreFlowUsers.getAssessmentRole().split(",");
        }
        if (!StringUtils.checkNull(assessorWeightStr)) {
            String[] assessorArr = assessorWeightStr.split(",");
            for (String assessorStr : assessorArr) {
                String[] split = assessorStr.split("\\*");
                scoreFlowUsers.setPrivType(Integer.parseInt(split[0]));
                if(privWeightMap.get(split[0])!=null){
                    scoreFlowUsers.setPrivWeight(Double.parseDouble(privWeightMap.get(split[0])));
                    String s = split[1];
                    String[] split1 = s.split("\\|");
                    // 设置考核人信息
                    scoreFlowUsers.setAssessor(split1[0]);
                    scoreFlowUsers.setAssessorWeight(Double.parseDouble(split1[1]));
                    scoreFlowUsers.setStatus(0);
                    if ("*".equals(role[roleNum].substring(role[roleNum].length() -1,role[roleNum].length()))){//最后一位是*说明传空
                        scoreFlowUsers.setAssessmentRole("");
                    }else {
                        scoreFlowUsers.setAssessmentRole(role[roleNum].split("\\*")[1]);
                    }
                    roleNum += 1;

                    // 查询考核人信息
                    paraMap.put("scoreFlowId",scoreFlowUsers.getScoreFlowId());
                    paraMap.put("assessor",scoreFlowUsers.getAssessor());
                    paraMap.put("userId",scoreFlowUsers.getUserId());
                    paraMap.put("privType",scoreFlowUsers.getPrivType());
                    paraMap.put("assessmentRole",scoreFlowUsers.getAssessmentRole());
                    List<ScoreFlowUsers> scoreFlowUsers1 = scoreFlowUsersMapper.selectFlowUsers(paraMap);
                    if(scoreFlowUsers1==null||scoreFlowUsers1.size()==0){ //判断是否为空 为空可以直接添加
                        scoreFlowUsersMapper.insertSelective(scoreFlowUsers);
                    } else {
                        // 该条件为存在的情况下 如果存在就更新
                        ScoreFlowUsers scoreFlowUsers2 = scoreFlowUsers1.get(0);
                        if(scoreFlowUsers2!=null){
                            scoreFlowUsers.setId(scoreFlowUsers2.getId());
                            scoreFlowUsers.setStatus(null);
                            scoreFlowUsersMapper.updateByPrimaryKeySelective(scoreFlowUsers);
                            scoreFlowUsers.setId(null); // 初始化
                        }
                    }
                    newAssessor.put(scoreFlowUsers.getAssessor()+"_"+scoreFlowUsers.getPrivType()+"_"+scoreFlowUsers.getAssessmentRole(),scoreFlowUsers.getAssessorWeight());
                }
            }
            if(isSelfAssessment==1){
                // 查询考核人信息
                paraMap.put("scoreFlowId",scoreFlowUsers.getScoreFlowId());
                paraMap.put("assessor",scoreFlowUsers.getUserId());
                paraMap.put("userId",scoreFlowUsers.getUserId());
                paraMap.put("privType","4");
                List<ScoreFlowUsers> scoreFlowUsers1 = scoreFlowUsersMapper.selectFlowUsers(paraMap);
                if(scoreFlowUsers1==null||scoreFlowUsers1.size()==0){ //判断是否为空 为空可以直接添加
                    scoreFlowUsers.setPrivWeight(Double.parseDouble(privWeightMap.get("4")));
                    // 设置考核人信息
                    scoreFlowUsers.setAssessor(scoreFlowUsers.getUserId());
                    scoreFlowUsers.setAssessorWeight(Double.parseDouble("1"));
                    scoreFlowUsers.setStatus(0);
                    scoreFlowUsers.setId(null);
                    scoreFlowUsers.setPrivType(4);
                    scoreFlowUsersMapper.insertSelective(scoreFlowUsers);
                }
            }
        }
        // 查询出所有的考核人数据 判断是否有多余的考核人数据 进行删除
        if(newAssessor.size()>0){
            paraMap.remove("assessor");
            paraMap.remove("privType");
            paraMap.remove("assessmentRole");
            List<ScoreFlowUsers> scoreFlowUsers1 = scoreFlowUsersMapper.selectFlowUsers(paraMap);
            for(ScoreFlowUsers scoreFlowUser:scoreFlowUsers1){
                if(newAssessor.get(scoreFlowUser.getAssessor()+"_"+scoreFlowUser.getPrivType()+"_"+scoreFlowUser.getAssessmentRole())==null){
                    scoreFlowUsersMapper.deleteByPrimaryKey(scoreFlowUser.getId());
                }
            }
        }
    }

    /**
     * @接口说明: 查询该任务下的所有需要我评测的人员
     * @日期: 2020/7/20
     * @作者: 张航宁
     */
    public BaseWrapper selByAssessor(HttpServletRequest request,Integer scoreFlowId){
        BaseWrapper baseWrapper = new BaseWrapper();

        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

        Map<String,Object> map = new HashMap<>();
        map.put("assessor",user.getUserId());
        map.put("scoreFlowId",scoreFlowId);
        map.put("privType",request.getParameter("privType"));
        map.put("groupType",request.getParameter("groupType"));
        // 需要我评测的人员
        List<ScoreFlowUsers> scoreFlowUsers = scoreFlowUsersMapper.selectFlowUsers(map);

        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(scoreFlowId);

        // 查询出考核项目类别
        List<ScoreGroupWithBLOBs> scoreGroupWithBLOBs = scoreGroupMapper.selectByTypeId(String.valueOf(scoreFlowWithBLOBs.getGroupId()));

        List<Integer> itemIds = new ArrayList<>();
        for(ScoreGroupWithBLOBs scoreGroup:scoreGroupWithBLOBs){
            // 查询考核项目明细
            List<ScoreItem> scoreItems = scoreItemMapper.selectByTypeId(scoreGroup.getGroupId());

            // 遍历明细 获取itemIds数组
            for(int i=0;i<scoreItems.size();i++){
                // 根据flowId itemId 考核人userId 查询所有考核人的评分
                itemIds.add(scoreItems.get(i).getItemId());
            }
        }

        // 遍历被考核人 获取考核分数
        Integer[] itemIdsArr  = itemIds.toArray(new Integer[0]);
        for (ScoreFlowUsers scoreFlowUsers1: scoreFlowUsers) {
            String userId = scoreFlowUsers1.getUserId();
            if(!StringUtils.checkNull(userId)){
                Users users = usersMapper.SimplefindUsersByuserId(userId);
                if(users!=null){
                    scoreFlowUsers1.setUserName(users.getUserName());
                    scoreFlowUsers1.setDeptName(users.getDeptName());
                    if(users.getPostId()!=null&&users.getPostId()!=0){
                        UserPost userPostId = dutiesManagementMapper.getUserPostId(users.getPostId());
                        if(userPostId!=null){
                            scoreFlowUsers1.setPostName(userPostId.getPostName());
                        }
                    }
                }
            }

            if(!StringUtils.checkNull(scoreFlowUsers1.getIds())){
                scoreFlowUsers1.setIds(scoreFlowUsers1.getIds().replace(",","&"));
            }

            if(!StringUtils.checkNull(scoreFlowUsers1.getAssessorWeights())){
                NumberFormat percentInstance = NumberFormat.getPercentInstance();
                percentInstance.setMaximumFractionDigits(2);
                String[] split = scoreFlowUsers1.getAssessorWeights().split(",");
                StringBuilder assessorWeights = new StringBuilder();
                for (int i = 0; i < split.length; i++) {
                    assessorWeights.append(percentInstance.format(Float.parseFloat(split[i]))).append(",");
                }
                scoreFlowUsers1.setAssessorWeights(assessorWeights.toString());
            }

            if(!StringUtils.checkNull(scoreFlowUsers1.getPrivTypes())){
                String[] privTypes = scoreFlowUsers1.getPrivTypes().split(",");
                StringBuilder privTypeNames  = new StringBuilder();
                for (int i = 0; i < privTypes.length; i++) {
                    if(i>0){
                        privTypeNames.append(",");
                    }
                    switch (privTypes[i]){
                        case "1":
                            privTypeNames.append("上级");
                            break;
                        case "2":
                            privTypeNames.append("平级");
                            break;
                        case "3":
                            privTypeNames.append("下级");
                            break;
                    }
                }
                scoreFlowUsers1.setPrivTypNames(privTypeNames.toString());
            }

            List<ScoreFlowItem> scoreFlowItems = scoreFlowItemMapper.selectByItemIds(itemIdsArr,userId,scoreFlowUsers1.getAssessor(),scoreFlowId);
            scoreFlowUsers1.setScoreFlowItems(scoreFlowItems);
        }


        baseWrapper.setData(scoreFlowUsers);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @接口说明: 获取考核评分
     * @日期: 2020/7/22
     * @作者: 张航宁
     */
    public BaseWrapper selUserScoreDetail(Integer flowId,String userId){
        BaseWrapper baseWrapper = new BaseWrapper();

        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(flowId);

        if(scoreFlowWithBLOBs!=null){

            Map<String,Object> map = new HashMap<>();
            map.put("userId",userId);
            map.put("scoreFlowId",flowId);

            // 查询所有考核人
            List<ScoreFlowUsers> scoreFlowUsers = scoreFlowUsersMapper.selectFlowUsers(map);

            // 查询出考核项目类别
            List<ScoreGroupWithBLOBs> scoreGroupWithBLOBs = scoreGroupMapper.selectByTypeId(String.valueOf(scoreFlowWithBLOBs.getGroupId()));

            List<Integer> itemIds = new ArrayList<>();
            for(ScoreGroupWithBLOBs scoreGroup:scoreGroupWithBLOBs){
                // 查询考核项目明细
                List<ScoreItem> scoreItems = scoreItemMapper.selectByTypeId(scoreGroup.getGroupId());

                // 遍历明细 获取itemIds数组
                for(int i=0;i<scoreItems.size();i++){
                    // 根据flowId itemId 考核人userId 查询所有考核人的评分
                    itemIds.add(scoreItems.get(i).getItemId());
                }
            }

            Double realCount = 0.0;
            Double first=0.0;
            Double second=0.0;
            Double third=0.0;
            Double firstWeight=0.0;
            Double secondWeight=0.0;
            Double thirdWeight=0.0;
            // 遍历考核人 获取考核分数
            Integer[] itemIdsArr  = itemIds.toArray(new Integer[0]);
            for (ScoreFlowUsers scoreFlowUsers1: scoreFlowUsers) {
                Users users = usersMapper.SimplefindUsersByuserId(scoreFlowUsers1.getAssessor());
                if(users!=null){
                    scoreFlowUsers1.setAssessorName(users.getUserName());
                }
                List<ScoreFlowItem> scoreFlowItems = scoreFlowItemMapper.selectByItemIds(itemIdsArr,userId,scoreFlowUsers1.getAssessor(),flowId);
                scoreFlowUsers1.setScoreFlowItems(scoreFlowItems);
                if(scoreFlowUsers1.getScore()!=null){
                   realCount+=scoreFlowUsers1.getScore()*scoreFlowUsers1.getPrivWeight()*scoreFlowUsers1.getAssessorWeight();
                } else {
                    scoreFlowUsers1.setScore(0.0);
                }
                if(scoreFlowUsers1.getPrivType().equals(1)){//一级
                    first+=scoreFlowUsers1.getScore()*scoreFlowUsers1.getAssessorWeight();
                    firstWeight=scoreFlowUsers1.getPrivWeight();
                }else if(scoreFlowUsers1.getPrivType().equals(2)){//一级
                    second+=scoreFlowUsers1.getScore()*scoreFlowUsers1.getAssessorWeight();
                    secondWeight=scoreFlowUsers1.getPrivWeight();
                }else if(scoreFlowUsers1.getPrivType().equals(3)){//一级
                    third+=scoreFlowUsers1.getScore()*scoreFlowUsers1.getAssessorWeight();
                    thirdWeight=scoreFlowUsers1.getPrivWeight();
                }
            }
            Map returnMap=new HashMap();
            returnMap.put("first",first);
            returnMap.put("second",second);
            returnMap.put("third",third);
            baseWrapper.setObj(returnMap);
            baseWrapper.setData(scoreFlowUsers);
            baseWrapper.setMsg(String.valueOf(realCount));
        }

        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @接口说明: 查询被考核人的总分
     * @日期: 2020/7/23
     * @作者: 张航宁
     */
    public BaseWrapper selUserScoreCount(Integer flowId,String userId){
        BaseWrapper baseWrapper = new BaseWrapper();

        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(flowId);

        if(scoreFlowWithBLOBs!=null) {

            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            map.put("scoreFlowId", flowId);

            // 查询所有考核人
            List<ScoreFlowUsers> scoreFlowUsers = scoreFlowUsersMapper.selectFlowUsers(map);

            Double realCount = 0.0;
            // 遍历考核人 获取考核分数
            for (ScoreFlowUsers scoreFlowUsers1: scoreFlowUsers) {
                if(scoreFlowUsers1.getScore()!=null)
                    realCount+=scoreFlowUsers1.getScore()*scoreFlowUsers1.getPrivWeight()*scoreFlowUsers1.getAssessorWeight();
            }
            baseWrapper.setData(realCount);
        }
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }
    /**
     * create by:李善澳
     * description: 获取整体考核考核任务下所有人员关系表
     * create time: 2020-09-20 12:59
     * @return
     */
    public BaseWrapper getAllData(Integer flowId) {
        BaseWrapper baseWrapper = new BaseWrapper();
        ScoreFlowWithBLOBs scoreFlowWithBLOBs = scoreFlowMapper.selectByPrimaryKey(flowId);
        List<ScoreReport> resultData = new ArrayList<>();
        if (scoreFlowWithBLOBs != null) {
            if (!StringUtils.checkNull(scoreFlowWithBLOBs.getParticipant())) {
                List<Users> users = new ArrayList<>();
                // 把userId串拆分成数组
                String[] userIdArr = scoreFlowWithBLOBs.getParticipant().split(",");
                String[] deptIds = scoreFlowWithBLOBs.getParticipantDept().split(",");
                users = usersMapper.getUsersByUserIdsOrderByDeptId(userIdArr);

                for (Users user : users) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", user.getUserId());
                    map.put("scoreFlowId", scoreFlowWithBLOBs.getFlowId());

                    Map<String, Object> result = new HashMap<>();

                    List<ScoreFlowUsers> privUsers1 = new ArrayList<>(); // 上级
                    List<ScoreFlowUsers> privUsers2 = new ArrayList<>(); // 平级
                    List<ScoreFlowUsers> privUsers3 = new ArrayList<>(); // 下级

                    List<ScoreFlowUsers> scoreFlowUser = scoreFlowUsersMapper.selectFlowUsers(map);
                    for (ScoreFlowUsers sfu : scoreFlowUser) {
                        String assessor = sfu.getAssessor();
                        Users ass = usersMapper.SimplefindUsersByuserId(assessor);
                        if (users != null) {
                            sfu.setAssessorName(ass.getUserName());
                        }
                        if (sfu.getPrivType() == 1) {
                            privUsers1.add(sfu);
                        } else if (sfu.getPrivType() == 2) {
                            privUsers2.add(sfu);
                        } else if (sfu.getPrivType() == 3) {
                            privUsers3.add(sfu);
                        }
                    }
                    result.put("privUsers1", privUsers1);
                    result.put("privUsers2", privUsers2);
                    result.put("privUsers3", privUsers3);
                    int index = printArray(userIdArr, user.getUserId());//获取人员对应部门的下标
                    resultData.add(new ScoreReport(user.getUserId(), user.getUserName(), Integer.valueOf(deptIds[index]), departmentMapper.getDeptNameById(Integer.valueOf(deptIds[index])), result));
                }
            }
        }
        baseWrapper.setData(resultData);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }
    //遍历数组
    public static int printArray(String[] array,String value){
        for(int i = 0;i<array.length;i++){
            if(array[i].equals(value)){
                return i;
            }
        }
        return -1;//当if条件不成立时，默认返回一个负数值-1
    }
}
